package com.tuling.jucdemo.threadpool;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author :tangweiliang
 * @date : 2022/11/22 22:50
 * 未来的你会感谢现在努力的自己
 *
 * 周期性执行线程
 */
public class ScheduledThreadPoolExecutorExample {
    public static void main(String[] args) {
        ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
        Task task = new Task("任务");
        System.out.println("Created:" + task.getName());
//       executor.schedule(task, 2, TimeUnit.SECONDS);//延迟2秒执行任务 没有周期性
//        executor.scheduleWithFixedDelay(task, 0,2,TimeUnit.SECONDS); //任务+延迟 周期性的
        executor.scheduleAtFixedRate(task,0,1,TimeUnit.SECONDS); //延迟取最大值 稳定定时器
    }
}

class Task implements Runnable{
    private String name;
    public Task(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    AtomicInteger atomicInteger = new AtomicInteger();
    public void run() {
        atomicInteger.incrementAndGet();
        try{
            if(atomicInteger.get()>3){
                throw new NullPointerException();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
//        if(atomicInteger.get()>3){
//            throw new NullPointerException();//这个时候不能throw 要try catch 否则任务就不跑了 因为call() 里的run()没有try catch
//        }
        System.out.println("Excuting:"+ name +",Current Seconds:"+new Date().getSeconds());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
